export default {
	namespaced: true,
	
	state: () => ({
		// 模块中的数据只能通过自己的mutations函数进行修改
		//每一个元素都包含{goods_id, goods_name, goods_price, goods_count, goods_img, goods_state}
		cart: JSON.parse(uni.getStorageSync('cart') || '[]')
	}),
	
	mutations: {
		updateCart(state, my_cart) {
			state.cart = my_cart
			uni.setStorageSync('cart', JSON.stringify(state.cart))
		},
		
		addtoCart(state, goods) {
			const findResult = state.cart.find(x => x.goods_id === goods.goods_id)  //find会循环数组中所有元素
			if(!findResult) {
				state.cart.push(goods)
			}else {
				findResult.goods_count ++
			}
			console.log(state.cart)
			uni.setStorageSync('cart', JSON.stringify(state.cart))
		},
		updateRadio(state, goods) {
			const findResult = state.cart.find(x => x.goods_id === goods.goods_id) 
			if(findResult) {
				findResult.goods_state = !goods.goods_state
				uni.setStorageSync('cart', JSON.stringify(state.cart))
			}
		},
		updateNum(state, goods) {
			const findResult = state.cart.find(x => x.goods_id === goods.goods_id) 
			if(findResult) {
				findResult.goods_count = goods.goods_count
				uni.setStorageSync('cart', JSON.stringify(state.cart))
			}
		},
		deleteNum(state, goods_id) {
			state.cart = state.cart.filter(x => x.goods_id !== goods_id)
			uni.setStorageSync('cart', JSON.stringify(state.cart))
		},
		cart_all_choose(state, all_type) {
			state.cart.forEach(x => x.goods_state = all_type)
			uni.setStorageSync('cart', JSON.stringify(state.cart))
		}
	},
	
	getters: {
		total(state) {
			let c = 0
			state.cart.forEach(x => c += x.goods_count)
			return c
		},
		pay_total(state) {
			return state.cart.filter(x => x.goods_state).reduce((sum, item) => sum += item.goods_count, 0)
		},
		price(state) {
			let c = 0
			state.cart.filter(x => x.goods_state).forEach(x => c += x.goods_price * x.goods_count) 
			return c
		}
	}
	
}